package handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.net.URLDecoder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

public class ListFileHandler extends ChannelInboundHandlerAdapter
{
    private              File         dir;
    private              ObjectMapper mapper  = new ObjectMapper();
    private static final Charset      CHARSET = Charset.forName("utf8");

    public ListFileHandler(File dir)
    {
        this.dir = dir;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
    {
        FullHttpRequest fullHttpRequest = (FullHttpRequest) msg;
        String          uri             = fullHttpRequest.uri();
        uri = URLDecoder.decode(uri, "utf8");
        if (uri.equals("/"))
        {
            String[] list   = dir.list();
            String   s      = mapper.writeValueAsString(list);
            ByteBuf  buffer = ctx.alloc().buffer();
            buffer.writeBytes(s.getBytes(CHARSET));
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer);
            response.headers().add(HttpHeaderNames.CONTENT_TYPE, HttpHeaderValues.APPLICATION_JSON + ";" + HttpHeaderValues.CHARSET + "=utf8");
            response.headers().add(HttpHeaderNames.CONTENT_LENGTH, buffer.readableBytes());
            ctx.writeAndFlush(response);
            System.out.println("文件夹内容输出完毕");
        }
        else
        {
            ctx.fireChannelRead(msg);
        }
    }
}